package com.gyms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.classic.okhttp.beans.HVCardBean;
import com.classic.okhttp.beans.HVMyOrderInfoBean;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.adapter.MyCouponAdapterNew;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.CouponManger;
import com.gyms.manager.StateUtils;
import com.gyms.manager.StatisticsManager;
import com.gyms.manager.TitleManager;
import com.umeng.socialize.UMShareAPI;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import click.OnRecyclerViewItemClick;
import constant.EventConstant;
import utils.StringUtils;
import weight.ClearableEditText;
import weight.CommonEmptyView;
import weight.UiEvent;

/**
 * 我的卡券 ltx
 */
public class MyCouponActivityNew extends BaseActivity implements CommonEmptyView.UpdateClick, OnRecyclerViewItemClick, View.OnClickListener {
    @BindView(R.id.et_kouling)
    ClearableEditText etKouling;//优惠券口令
    @BindView(R.id.rv_coupon_list)
    RecyclerView mRvCouponList;//卡卷列表
    private HVMyOrderInfoBean mHVMyOrderInfoBean;//订单详情的bean
    private ArrayList<HVCardBean> mHVCardBeans = new ArrayList<>();
    private MyCouponAdapterNew mCouponAdapter;//卡卷的adapter

    @BindView(R.id.ev_coupon)
    CommonEmptyView mEvCoupon;//卡卷的空页面

    private boolean isHaveHistoryed;//是否已经显示历史记录了
    private boolean isMyCoupon=true;//是否是我的卡卷页面  true 是我的卡卷页面 false 是我的订单页面
    private CouponManger mCouponManger;//卡卷管理类
    private Integer mSelectCardId;//选中的卡卷Id

    private ArrayList<Integer> mAvailableCouponList;//符合该订单的卡卷Id

    private final static int S_SACN_CODE=100;

    private boolean isCanScan=true;//暂时允许扫码

    @Override
    protected void setTitleTheme() {
        mTheme = TitleManager.TitleTheme.White;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_my_coupon_new;
    }

    @Override
    protected void initView() {
        initData();
        doInitView();
        createLoadingView(getResources().getString(R.string.str_loading), true);
        setTitle(getString(R.string.str_my_coupon));
        setBack();
        initCouponAdapter();
        if(isCanScan){
            mTitleManager.setRightViewOnclick(this);
            mTitleManager.setRightView(R.mipmap.icon_saoma);
        }
    }

    private void doInitView() {
        etKouling.setPadingLeft(mContext,10);//设置输入框10dp的Pading
    }

    private void initData() {
        mCouponManger=CouponManger.getInstance();
        Bundle mBundle = getIntent().getExtras();
        if (null != mBundle) {
            mHVMyOrderInfoBean = (HVMyOrderInfoBean) mBundle.getSerializable(Constants.FALG_INTENT_ORDER_DETAIL);//订单详情的bean
            String mFlagConfirm = mBundle.getString(Constants.FLAG_GO_MYCARD);//从订单详情跳进来
            isMyCoupon = StringUtils.isNull(mFlagConfirm);//我的卡卷页面
            mSelectCardId = mBundle.getInt(Constants.COUPONID);//Cardbean
            mAvailableCouponList= (ArrayList<Integer>) mBundle.getSerializable(Constants.S_AVAILABLE_COUPON_LIST);
        }
    }

    /**
     * 初始化我的卡卷适配器
     */

    private void initCouponAdapter() {
        mCouponAdapter=new MyCouponAdapterNew(this,isMyCoupon);
        mCouponAdapter.setHVCardBeans(mHVCardBeans);
        LinearLayoutManager mLlManager=new LinearLayoutManager(this);
        mLlManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvCouponList.setLayoutManager(mLlManager);
        mRvCouponList.setAdapter(mCouponAdapter);

    }

    @Override
    protected void setListener() {
        mEvCoupon.setUpDateClick(this);
        mCouponAdapter.setOnRecyclerViewItemClick(this);
    }

    @Override
    protected void processLogic() {
        reqCardList();
    }


    /**
     * 添加
     */
    @OnClick(R.id.tv_add)
    public void onClick() {
        doAddUserCard();
    }

    /**
     * 查询优惠券
     */
    private void reqCardList() {
        loadingView.show();
        IUserService.getCardList(this, "", false, new ObjectCallback<ArrayList<HVCardBean>>() {
            @Override
            public void onSuccess(ArrayList<HVCardBean> response, String message) {
                if (null != loadingView) {
                    loadingView.dismiss();
                }
                if(!StringUtils.isNull(response)){
                    dismissEmptyView(mRvCouponList,mEvCoupon);
                    doAddCardBeans(response);
                    mCouponAdapter.notifyDataSetChanged();

                }else{
                    showEmptyView(mRvCouponList,mEvCoupon, Constants.TYPE_NOME);
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVCardBean> response, String errorMessage) {
                dialogDis();
                showEmptyView(mRvCouponList,mEvCoupon, code);
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
                showEmptyView(mRvCouponList,mEvCoupon, Constants.NO_NET);
            }
        });
    }

    /**
     * 数据拼接 如果是我的卡卷页面 显示历史优惠券  如果是订单优惠券选择页面就 实现是否可选择
     * @param response cardBeans
     */

    private void doAddCardBeans(ArrayList<HVCardBean> response) {
         mHVCardBeans.clear();
        if(isMyCoupon){//我的卡卷
            addHistoryBean(response);
            mHVCardBeans.addAll(response);
        }else{//订单选择卡卷
            mCouponManger.initData(mHVMyOrderInfoBean, response ,mAvailableCouponList);
            ArrayList<HVCardBean> mTempCardBeans;
            mTempCardBeans= mCouponManger.orderStatue();
                if(!StringUtils.isNull(mSelectCardId)){//已经有选择的卡卷id
                    mTempCardBeans= mCouponManger.getIsSelctedList(mSelectCardId);
                }
                mHVCardBeans.addAll(mTempCardBeans);
                mCouponAdapter.notifyDataSetChanged();
        }
    }

    private void addHistoryBean(ArrayList<HVCardBean> response) {
        for(int pos=0;pos<response.size();pos++){
            HVCardBean mCardBean=response.get(pos);
            if(mCardBean.getIsWork().value!=0){
                if(!isHaveHistoryed){
                    HVCardBean mHvCardBean=new HVCardBean();
                    mHvCardBean.setIsHaveHistory(true);
                    response.add(pos,mHvCardBean);
                    isHaveHistoryed=true;
                }
            }
        }

    }


    /**
     * 领取优惠券
     */
    private void doAddUserCard() {
        String code = etKouling.getText().toString().trim();
        if (StringUtils.isNull(code)) {
            ToastUtil.showToast(mContext, "请输入口令");
            return;
        }
        //卡券添加统计
        HashMap<String, String> map = new HashMap<>();
        map.put("keyword", code);
        StatisticsManager.onEvent(mContext, StatisticsManager.MyCard_Add, map);
        addUserCard(code);

    }

    /**
     * 领取优惠券接口
     * @param code 领取口令
     */

    private void addUserCard(String code) {
        loadingView.show();
        IUserService.addUserCard(this, code, false, new ObjectCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean response, String message) {
                if (response) {
                    reqCardList();
                } else {
                    dialogDis();
                    ToastUtil.showToast(mContext, "优惠券添加失败");
                }
            }

            @Override
            public void onErrorT(int code, Boolean response, String errorMessage) {
                dialogDis();
                ToastUtil.showToast(mContext, errorMessage);
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
            }
        });
    }

    @Override
    public void onUpdateClick() {
        loadingView.show();
        reqCardList();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        hideKeyBoard(ev);//隐藏软键盘
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onRecyclerItemClick(RecyclerView view, int pos) {
        if(view==mRvCouponList){//
            HVCardBean mTempBean=mHVCardBeans.get(pos);
            if (mTempBean.getIsUseAble()) {
                    if (mTempBean.getIsSelcted()) {//以选中的状态 取消使用优惠券
                        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_COME_BACK_CONFIRM, null));
                    } else {//使用优惠券
                        EventBus.getDefault().post(new UiEvent(EventConstant.FLAG_COME_BACK_CONFIRM, mTempBean));
                    }
                    onBackPressed();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == S_SACN_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    String mCouponCode=StateUtils.doSpliteCode(result);
                    if(StringUtils.isNull(mCouponCode)){
                        Toast.makeText(this, "该码不可用", Toast.LENGTH_LONG).show();
                    }else {
                        addUserCard(mCouponCode);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_img_right://扫码
                doScan();
                break;
        }
    }

    /**
     * 扫码
     */

    private void doScan() {
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, S_SACN_CODE);
    }

}
